package com.example.uploadtest.hsf;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {

    /**
     * 通用导出方法
     *
     * @param response  Http响应对象
     * @param fileName  导出文件名（不带后缀）
     * @param sheetName sheet名称
     * @param data      数据列表
     * @param clazz     数据模型类
     */
    public static <T> void export(HttpServletResponse response,
                                  String fileName,
                                  String sheetName,
                                  List<T> data,
                                  Class<T> clazz) throws IOException {


        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), clazz)
                .autoCloseStream(false)
                .sheet(sheetName)
                .doWrite(data);
    }
}
